package cn.itcast.wushangxiantu.Fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.BaseAdapter.FuBenFangJianAdapter;
import cn.itcast.wushangxiantu.UserData.FuBenFangJian;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FuBenDaTin#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FuBenDaTin extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private View view;
    private Context context;
    private ViewHolder viewHolder;
    private FuBenFangJianAdapter adapter;
    private FuBenFangJian fuBenFangJian;
    private int ditu;
    private int dj;
    private int num;

    public FuBenDaTin() {
        // Required empty public constructor
    }

    public FuBenDaTin(Context context) {
        this.context = context;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FuBenDaTin.
     */
    // TODO: Rename and change types and number of parameters
    public static FuBenDaTin newInstance(String param1, String param2) {
        FuBenDaTin fragment = new FuBenDaTin();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_fu_ben_da_tin, container, false);
        viewHolder = new ViewHolder(view);
        return view;
    }

    class ViewHolder {
        public View rootView;
        public Spinner spDiTu;
        public Spinner spDj;
        public Button btnSouSuo;
        public ListView lv;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.spDiTu = (Spinner) rootView.findViewById(R.id.spDiTu);
            this.spDj = (Spinner) rootView.findViewById(R.id.spDj);
            this.btnSouSuo = (Button) rootView.findViewById(R.id.btnSouSuo);
            this.lv = (ListView) rootView.findViewById(R.id.lv);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    num=i;
                    getFangJianXinXi(fuBenFangJian.getFangJian().get(i).getFj_id());

                }
            });

            btnSouSuo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ditu=spDiTu.getSelectedItemPosition();
                    dj=spDj.getSelectedItemPosition();
                    getFangJianYuLan(ditu,dj);
                }
            });
        }

        private void getFangJianXinXi(int fj_id) {
            //获取也就是房主信息
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "fj_id=" + fj_id + "&need=GetFangZhuName"+"&dj="+dj, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.v("name1", e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String src = response.body().string();
                    Log.v("name2", src);
                    User dj = null;
                    try {
                        dj = new Gson().fromJson(src, User.class);
                    } catch (Exception e) {

                    }
                    Message message = new Message();
                    message.obj = dj;
                    message.what = 2;
                    handler.sendMessage(message);
                }
            });
        }

        private void getFangJianYuLan(int ditu,int dj) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "ditu=" + ditu + "&need=YuLanFJ"+"&dj="+dj, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.v("yulan1", e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String src = response.body().string();
                    Log.v("yulan2", src);
                    FuBenFangJian dj = null;
                    try {
                        dj = new Gson().fromJson(src, FuBenFangJian.class);
                    } catch (Exception e) {

                    }
                    Message message = new Message();
                    message.obj = dj;
                    message.what = 1;
                    handler.sendMessage(message);
                }
            });
        }
        Handler handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                switch (message.what){
                    case 1:
                        fuBenFangJian= (FuBenFangJian) message.obj;
                        if (null!=fuBenFangJian){
                            if (null==adapter){
                                adapter=new FuBenFangJianAdapter(context,fuBenFangJian);
                            }
                            adapter.setFuBenFangJian(fuBenFangJian);
                            lv.setAdapter(adapter);
                        }else {
                            ToastUtil.toast(context,"服务器炸了");
                        }
                        break;
                    case 2:
                        User user= (User) message.obj;
                        if (null!=user){
                            String content="房主:"+user.getStw()+"\n地图:"+spDiTu.getSelectedItem().toString()+
                                    "\n难度:"+spDj.getSelectedItem().toString()+"\n门槛小怪:"+fuBenFangJian.getFangJian().get(num).getMindj()+"级\n"+
                                    "人数:"+fuBenFangJian.getFangJian().get(num).getNumber();
                            GeneralDialog("房间信息",content,"加入房间",1);

                        }else {
                            ToastUtil.toast(context,"服务器炸了");
                        }
                        break;
                    case 3:
                         user= (User) message.obj;
                        if (null!=user){
                            ToastUtil.toast(context,user.getStw());
                            EventBus.getDefault().post(new MessageEvent("getFuBenNum"));
                        }else {
                            ToastUtil.toast(context,"服务器炸了");
                        }
                        break;
                }
                return false;
            }
        });
        public void GeneralDialog(String head, String content, String buttontext, final int num) {
            /**
             * 普通对话框
             * 1标题
             * 2内容
             */
            AlertDialog dialog;
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(head)
                    .setMessage(content)
                    .setPositiveButton(buttontext, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (num==1){
                                //调用编辑框写密码
                                GeneralDialog("输入房间密码");
                            }
                            dialogInterface.dismiss();
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }
        private void GeneralDialog(final String title) {
            /**
             * 编辑框
             * 1标题
             */
            AlertDialog dialog;
            final EditText editText = new EditText(context);
            editText.setLines(1);
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
            String content = null;

            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(content)
                    .setView(editText)
                    .setTitle(title)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                                if (editText.getText().toString().trim().length() > 20) {
                                    ToastUtil.toast(context, "长度过长了");
                                    return;
                                }
                            //加入房间
                            JiaRuFangJian(Login.getUser().getUsernumber(),editText.getText().toString(),fuBenFangJian.getFangJian().get(num).getFj_id());
                            dialogInterface.dismiss();
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }

        private void JiaRuFangJian(String usernumber, String toString, int fj_id) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&userNumber="+usernumber+"&password=" + toString + "&need=JiaRuFJ"+"&fj_id="+fj_id, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.v("jiaru1", e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String src = response.body().string();
                    Log.v("jiaru2", src);
                    User dj = null;
                    try {
                        dj = new Gson().fromJson(src, User.class);
                    } catch (Exception e) {

                    }
                    Message message = new Message();
                    message.obj = dj;
                    message.what = 3;
                    handler.sendMessage(message);
                }
            });
        }
    }
}